package com.phonetools.commonutils.number;

import java.nio.ByteOrder;

public class ByteArrayUtils {

    protected static byte[] shortToByteArray(short input, ByteOrder order) {
        byte[] output = new byte[2];
        if (order == ByteOrder.LITTLE_ENDIAN) {
            output[0] = (byte) (input & 0xFF);
            output[1] = (byte) ((input >> 8) & 0xFF);
        } else {
            output[1] = (byte) (input & 0xFF);
            output[0] = (byte) ((input >> 8) & 0xFF);
        }
        return output;
    }

    protected static byte[] intToByteArray(int input, ByteOrder order) {
        byte[] output = new byte[4];
        if (order == ByteOrder.LITTLE_ENDIAN) {
            output[0] = (byte) (input & 0xff);
            output[1] = (byte) (input >> 8 & 0xff);
            output[2] = (byte) (input >> 16 & 0xff);
            output[3] = (byte) (input >> 24 & 0xff);
        } else {
            output[3] = (byte) (input & 0xff);
            output[2] = (byte) (input >> 8 & 0xff);
            output[1] = (byte) (input >> 16 & 0xff);
            output[0] = (byte) (input >> 24 & 0xff);
        }
        return output;
    }

    protected static short byteArrayToShort(byte[] input, ByteOrder order) {
        if (input.length != 2) throw new NumberFormatException("ByteArray Size != 2");
        if (order == ByteOrder.LITTLE_ENDIAN) {
            return (short) ((input[0] & 0xff) + ((input[1] & 0xff) << 8));
        } else {
            return (short) ((input[1] & 0xff) + ((input[0] & 0xff) << 8));
        }
    }

    protected static int byteArrayToInt(byte[] input, ByteOrder order) {
        if (input.length != 4) throw new NumberFormatException("ByteArray Size != 4");
        if (order == ByteOrder.LITTLE_ENDIAN) {
            return ((input[0] & 0xff) + ((input[1] & 0xff) << 8)) + ((input[2] & 0xff) << 16) + ((input[3] & 0xff) << 24);
        } else {
            return ((input[3] & 0xff) + ((input[2] & 0xff) << 8)) + ((input[1] & 0xff) << 16) + ((input[0] & 0xff) << 24);
        }
    }
}
